package com.ly.mpayment.rest.up.hebao;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.SysConfig;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.sys.ISysConfigService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.task.TaskScan;
import com.ly.mpayment.rest.recharge.RechargeRest;
import com.ly.mpayment.rest.up.honglu.HongLuRest;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Path("hebao")
public class HeBaoRest {
    Logger logger = Logger.getLogger(HeBaoRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    ISysConfigService configService;

    @Path("callBack")
    @POST
    public String callBack(String data) {
        return "0";
    }

    public static void main(String[] args) {
        String phone = "18782435842";
        String begDt = "20221010";
        String endDt = "20221014";
        String cookie = "sid=70b077d6-6c49-4a50-9f18-2bd7548e402e";
        String filename = new HeBaoRest().generateFile(phone,"5");
        new HeBaoRest().heartYd(cookie);
        new HeBaoRest().queryOrder(cookie,phone,begDt,endDt);
        new HeBaoRest().uploadFile(cookie,filename,phone);
    }

    /**
     * 返回流水号 1-2分钟后查询
     * @param cookie
     * @param phoneNum
     * @param begDt
     * @param endDt
     * @return
     */
    public String queryOrder(String cookie,String phoneNum,String begDt,String endDt){
        logger.info("hebao_queryOrder:"+phoneNum);
        String t = System.currentTimeMillis()+"";
        String url = "https://www.cmpay.com/merchant/pes/enterprise_payment_record_query.xhtml?MER_NO_PAST=&BEG_DT="+begDt+
        "&END_DT="+endDt+"&PE_STATUS=A&RCV_SEH_MBL_NO="+phoneNum+"&viewCode=ajax&t="+t;
        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie",cookie);
        headers.put("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36");
        headers.put("format","http+json");
        String result = HttpClient.httpGet10086Url(url,headers);
        Document document = Jsoup.parse(result, "utf-8");
        String resultView = document.select("tbody[id=trans_box]").html();
        String text = document.select("input[name=TOT_REC_NUM]").val();
        //boolean attr = document.select("tbody[id=trans_box]").contains("缴费成功");
        phoneNum = phoneNum.substring(0,3)+"\\*\\*\\*\\*"+phoneNum.substring(7,11);
        Pattern phone = Pattern.compile(phoneNum);
        Matcher phonem = phone.matcher(resultView);
        JSONObject liushuihao = new JSONObject();
        while (phonem.find()) {
            liushuihao.put("phonem", phonem.group());
            break;
        }
        phone = Pattern.compile("\\d{24}");
        phonem = phone.matcher(resultView);
        while (phonem.find()) {
            liushuihao.put("liushuihao", phonem.group());
            //只取第一个
            break;
        }
        if(liushuihao.containsKey("liushuihao")){
            logger.info(phoneNum+","+liushuihao.getString("liushuihao"));
            return liushuihao.getString("liushuihao");
        }
        return "";
    }

    /**
     * 订单查询
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        if(DateUtils.addMinutes(3,upOrder.getCreatetime()).getTime() < new Date().getTime()){
            String start = new DateUtils().toTimeStampMonthDay(upOrder.getCreatetime());
            String orderNum = queryOrder(CookieRedis.get("ChinaMobileHeBaoToken"),upOrder.getUpphonenum(),start,start);
            if(!StringUtils.isBlank(orderNum)){
                upOrder.setRemark(orderNum);
                RechargeRest.successUpOrder.add(upOrder);
            }
        }
    }

    @Autowired
    private TaskScan taskScan;
    /**
     * 心跳 检查余额
     */
    public String heartYd(String cookie){
        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie",cookie);
        headers.put("Content-Type","application/x-www-form-urlencoded");
        String payment_menu = "https://www.cmpay.com/merchant/pes/enterprise_payment_menu.xhtml";
        String result = HttpClient.httpGet10086Url(payment_menu,headers);
        Document document = Jsoup.parse(result, "utf-8");
        //查询余额
        String account1 = document.select("font[id=account1]").html();
        if(StringUtils.isBlank(account1)){
            //taskScan.sendMsg("和包离线");
            logger.info("heartYd_离线");
            return "";
        }
        logger.info("heartYd_余额:"+account1);
        return account1;
    }

    /**
     * 上传
     * @param cookie
     * @param filename
     * @param phonenum
     * @return
     */
    public String uploadFile(String cookie,String filename,String phonenum){
        String file = "https://www.cmpay.com/filmer/rpm.upload";
        HashMap<String, Object> paramMap = new HashMap<>();
        //文件上传只需将参数中的键指定（默认file），值设为文件对象即可，对于使用者来说，文件上传与普通表单提交并无区别
        paramMap.put("file", FileUtil.file(filename));
        //{'errCode':'3','errMsg':'不允许上传同名文件，请更名后重新上传','new_fil_nm':'null','old_fil_nm':'999220815147853_20221011_105.xls','int_down_url':'/mer/rpm.intDownload'}
        String result = HttpUtil.post(file, paramMap);
        //{'errCode':'10','errMsg':'交易成功','new_fil_nm':'202210140043099465.xls','old_fil_nm':'999220815147853_20221014_105.xls',
        // 'int_down_url':'/rpm.intDownload?file=202210140043099465.xls'}
        if(!StringUtils.isBlank(result)){
            JSONObject body = JSONObject.fromObject(result);
            logger.info("uploadFile:"+phonenum+","+result);
            if(body.getString("errCode").equals("10")){
//                com.alibaba.fastjson.JSONObject data = new com.alibaba.fastjson.JSONObject();
//                data.put("new_fil_nm",body.getString("new_fil_nm"));
//                data.put("old_fil_nm",body.getString("old_fil_nm"));
//                //int_down_url=/rpm.intDownload?file=202210140043102594.xls
//                data.put("int_down_url",body.getString("int_down_url"));
//                data.put("t",System.currentTimeMillis());
                //错误码
                //正确的地址 https://www.cmpay.com/merchant/pes/enterprise_payment_file_storage.xhtml?viewCode=json&new_fil_nm=202210140043114870.xls&old_fil_nm=999220815147853_20221014_11120.xls&int_down_url=/rpm.intDownload?file=202210140043114870.xls&FLAG_BSP=Y&CURRENTPAGE=Y&t=1665738576829
                //https://www.cmpay.com/merchant/pes/enterprise_payment_file_storage.xhtml?viewCode=json&FLAG_BSP=Y&CURRENTPAGE=Y&int_down_url=/rpm.intDownload?file=202210140043115149.xls&new_fil_nm=202210140043115149.xls&old_fil_nm=999220815147853_20221014_11121.xls&t=1665738682484
                String queryFile = "https://www.cmpay.com/merchant/pes/enterprise_payment_file_storage.xhtml?viewCode=json" +
                        "&new_fil_nm="+ URLDecoder.decode(body.getString("new_fil_nm")) +"&old_fil_nm="+
                        URLDecoder.decode(body.getString("old_fil_nm"))+"&int_down_url=" +
                        body.getString("int_down_url")+"&FLAG_BSP=Y&CURRENTPAGE=Y&t="+
                        System.currentTimeMillis();
                Map<String, String> headers = new HashMap<>();
                headers.put("Cookie",cookie);
                String getResult = HttpClient.httpGet10086Url(queryFile,headers);
                Pattern phone = Pattern.compile("PTC10801:");
                Matcher phonem = phone.matcher(getResult);
                while (phonem.find()) {
                    //文件名格式不正确，请使用正确的商户编号修改文件名后重新上传
                    logger.info("提交文件错误:"+phonenum);
                    return "failt提交文件错误";
                }
                phone = Pattern.compile("PTC10800:");
                phonem = phone.matcher(getResult);
                while (phonem.find()) {
                    //文件名格式不正确，请使用正确的文件名重新上传
                    logger.info("文件名格式不正确:"+phonenum);
                    return "failt文件名格式不正确";
                }
                //BAT_NO
                logger.info("getResult:"+phonenum+","+getResult);
                try{
                    JSONObject payment = JSONObject.fromObject(getResult);
                    if(payment.containsKey("BAT_NO") && !StringUtils.isBlank(payment.getString("BAT_NO"))){
                        String commit = "https://www.cmpay.com/merchant/pes/enterprise_payment_submit.xhtml";
                        return commitOrder(payment.getString("BAT_NO"),commit,cookie);
                    }
                }catch (Exception e){
                    //e.printStackTrace();
                    return "failt提交失败";
                }
            }else{
                //上传失败
                logger.info(body.getString("errMsg"));
                return "failt"+body.getString("errMsg");
            }
        }else{
            logger.info(result);
            return "failt";
        }
        return "failt";
    }

    /**
     * 提单 返回单号 失败返回 :failt+"xxx"
     * @param batNo
     * @param urls https://www.cmpay.com/merchant/pes/enterprise_payment_submit.xhtml
     * {"CMPRST":"-1","USR_ID":"89900381371","IP_ADDR":"172.29.255.6","MERC_ID":"999220815147853","MERC_CNM":"成都最黑科技有限公司",
     * "AC_NO":"1081990001181263228","USR_CNM":"成都最黑科技","SMS_FLG":"1","APP_CLS":"002","MER_INF":{"USR_ID":"89900381371","FUNC_STR":
     *   "160010|160011|160030|160050|160060|160071|160072|160073|160080|160100|160110|160130|160131|160140|160141|160160|160190|160220|160224|160225|160226|160227|160228|160229|160230|160231|180020|180060|180070|180111|190010
     * |190014|200010|200020|200030|200033|200040|200050|200080|210009|210040|210050|210060|210070|210080|","MERC_CNM":"成都最黑科技有限公司",
     * "MERC_ID":"999220815147853","USR_CNM":"成都最黑科技","SUP_MER_STR":"999220815147853|","MODULE_STR":"160|180|190|200|210|","USR_NO":
     * "200000147853"},"SUP_MER_STR":"999220815147853|","MODULE_STR":"160|180|190|200|210|","BAT_NO":"221014668583843121","OUT_DAT":
     * [{"NOT_TX_AVA_BAL":"0.00","BAL":"0.00","STL_BAL":"0.00","CAP_TYP":"1","RED_BACK_BAL":"0.00","UAVA_BAL":"0.00","CUR_AC_BAL":"0.00"},
     * {"NOT_TX_AVA_BAL":"0.00","BAL":"0.00","STL_BAL":"0.00","CAP_TYP":"2","RED_BACK_BAL":"0.00","UAVA_BAL":"0.00","CUR_AC_BAL":"0.00"},
     * {"NOT_TX_AVA_BAL":"0","BAL":"59.6","STL_BAL":"59.6","CAP_TYP":"6","RED_BACK_BAL":"0.00","UAVA_BAL":"0","CUR_AC_BAL":"59.6","UPD_DT":
     * "20221011"},{"NOT_TX_AVA_BAL":"0.00","BAL":"0.00","STL_BAL":"0.00","CAP_TYP":"3","RED_BACK_BAL":"0.00","UAVA_BAL":"0.00","CUR_AC_BAL":"0.00"}
     * ,{"NOT_TX_AVA_BAL":"0.00","BAL":"0.00","STL_BAL":"0.00","CAP_TYP":"7","RED_BACK_BAL":"0.00","UAVA_BAL":"0.00","CUR_AC_BAL":"0.00"},
     * {"NOT_TX_AVA_BAL":"0.00","BAL":"0.00","STL_BAL":"0.00","CAP_TYP":"8","RED_BACK_BAL":"0.00","UAVA_BAL":"0.00","CUR_AC_BAL":"0.00"}],
     * "LOG_START_TIME":"20221014154127631","BAL3":"59.6","FUNC_STR":"160010|160011|160030|160050|160060|160071|160072|160073|160080|160100
     * |160110|160130|160131|160140|160141|160160|160190|160220|160224|160225|160226|160227|160228|160229|160230|160231|180020|180060|180070
     * |180111|190010|190014|200010|200020|200030|200033|200040|200050|200080|210009|210040|210050|210060|210070|210080|","RSP_AJX":"TRUE",
     * "CAP_TYP":"6","TXN_CD":"PTS5017024","INP_DAT":{"MERC_ID":"999220815147853","CAP_TYP":"6","MBL_NO":"","USR_NO":""},"VIEWCODE":"json",
     * "GWA":{"CUR_AC_DT":"20221014","_BAT_NO":"202210140025309377","TX_TYP":"","LAST_AC_DT_FLG":"D","TRM_ID":"","CNL_TX_CD":"","OPR_ID":"",
     * "MSG_DAT":"","TX_CD":"PTS5017024","OLD_JRN_NO":"","JRN_SEQ":"1","MSG_TYP":"N","MSG_CD":"PTC00000","LAST_AC_DT2_FLG":"D","VIEWCODE":"json",
     * "DOMAIN":"www.cmpay.com","AC_DT":"20221014","BUS_TYP":"","PRD_CD":"","LAST_AC_DT":"20221013","TX_DT":"20221014","VER_NO":"V1.0.0",
     * "WIN_SW_TM":"000000","CUR_AC_DT_FLG":"D","WIN_MOD":"1","WIN_STS":"N","TX_TM":"154127","NEXT_AC_DT":"20221015","SYS_CNL":"CMPAY",
     * "NEXT_AC_DT_FLG":"D","AP_CD":"","WIN_DT2":"20221015","TXN_MOD":"O","WIN_BEG_TM":"230000","WIN_DT1":"20221014","JRN_NO":"221014668583909332",
     * "BUS_CNL":"CMPAY","WIN_END_TM":"001000","LAST_AC_DT2":"20221012"},"SMS_CD":"000"}
     */
    public String commitOrder(String batNo,String urls,String cookie){
        String t = System.currentTimeMillis()+"";
        String url = urls+"?viewCode=json&SMS_FLG=on&BAT_NO="+batNo+"&SMS_REC_NUM=0&SMS_CD=000&t="+t;
        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie",cookie);
        headers.put("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36");
        headers.put("format","http+json");
        String result = HttpClient.postUrl10086Form(url,"",headers);
        //{"RSP_AJX":"TRUE","GWA":{"MSG_CD":"PTC10807","MSG_INF":"提交失败，手机号码为非移动号码或单笔额度超限"}}
        //MSG_CD=PTC00000 表示成功
        if(!StringUtils.isBlank(result)) {
            JSONObject body = JSONObject.fromObject(result);
            //提交成功
            if(body.getJSONObject("GWA").getString("MSG_CD").equals("PTC00000")){
                logger.info("提交成功:"+body.getString("BAT_NO"));
//                String phone = "18782435842";
//                String begDt = "20221010";
//                String endDt = "20221014";
//                queryOrder(cookie,phone,begDt,endDt);
                return body.getString("BAT_NO");
            }else{
                String msg = body.getJSONObject("GWA").containsKey("MSG_INF") ? body.getJSONObject("GWA").getString("MSG_INF") : body.getJSONObject("GWA").getString("MSG_CD");
                logger.info(batNo+","+msg);
                return "failt"+msg;
            }
        }else{
            logger.info(result);
             return "failt"+"提交失败";
        }
    }

    public void commitOrder(UpOrder order, UpShopInfo shop){
        UpOrder product = upOrderService.findOrderProduct(order.getUporderuuid());
        if (product != null) {
            try{
                logger.info("commitOrder:{}"+order.getUpphonenum());
                String filename = generateFile(product.getUpphonenum(),product.getUpShopPro().getUpfacevalue());
                logger.info("generateFile:{}"+order.getUpphonenum());
                String balance = heartYd(CookieRedis.get("ChinaMobileHeBaoToken"));
                logger.info("heartYd:{}"+order.getUpphonenum());
                if(!StringUtils.isBlank(balance) && Float.valueOf(balance) >= Float.valueOf(product.getUpShopPro().getUpfacevalue())){
                    String numOrder = uploadFile(CookieRedis.get("ChinaMobileHeBaoToken"),filename,product.getUpphonenum());
                    logger.info("numOrder:{}"+order.getUpphonenum()+","+numOrder);
                    if(!numOrder.contains("failt")){
//                        this.upOrderService.updateUpOrderMsg(order,numOrder,"提交成功");
                        order.setRemark(numOrder);
                        RechargeRest.successUpOrder.add(order);
                    }else{
                        //order.setRemark(numOrder);
                        //RechargeRest.failtUpOrder.add(order);
                        upOrderService.updateUpOrderArtificial(order,"",numOrder);
                    }
                }else{
                    logger.info("离线失败或余额不足:"+order.getUpphonenum());
                    //order.setRemark("离线失败或余额不足");
                    //RechargeRest.failtUpOrder.add(order);
                    upOrderService.updateUpOrderArtificial(order,"","离线失败或余额不足");
                }
            }catch (Exception e){
                e.printStackTrace();
                //order.setRemark("提交失败"+e.getMessage());
                //RechargeRest.failtUpOrder.add(order);
                upOrderService.updateUpOrderArtificial(order,"","提交失败转人工");
            }
        }
    }

    /**
     * 每日从00开始
     * @return
     */
    public synchronized String getIndex(){
        String toTimeStampMonthDay = new DateUtils().toTimeStampMonthDay();
        String index[] = CookieRedis.get("ChinaMobileHeBaoIndex").split("_");
        String num = Integer.valueOf(index[0]) == 0 ? "01" : Integer.valueOf(index[0]) + 1 +"";
        if(Integer.valueOf(index[1]) < Integer.valueOf(toTimeStampMonthDay)){
            num = 0 == 0 ? "01" : Integer.valueOf(index[0]) + 1 +"";
            //每天第一次初始化
            SysConfig config = configService.findByAttr("ChinaMobileHeBaoIndex");
            if(config != null) {
                config.setAttrValue(num + "_" + toTimeStampMonthDay);
                configService.updateSysConfig(config);
            }
        }
        num = num.length() == 1 ? "0"+num : num;
        //每日第一单从数据库获取
        CookieRedis.addCookie("ChinaMobileHeBaoIndex",num+"_"+toTimeStampMonthDay);

        SysConfig config = configService.findByAttr("ChinaMobileHeBaoIndex");
        if(config != null) {
            config.setAttrValue(num + "_" + toTimeStampMonthDay);
            configService.updateSysConfig(config);
        }
        return num;
    }
    /**
     * 生成订单文件 并且返回路径
     * 上传代缴文件：文件命名规则：商户编号(15位)_日期(8位)_序号(2位).xls
     * @param phone
     * @param price
     * @return
     */
    public String generateFile(String phone,String price){
        String fileName = CookieRedis.get("ChinaMobileHeBaoNum")+"_"+new DateUtils().toTimeStampMonthDay()+"_"+getIndex();
        String filePath = CookieRedis.get("ChinaMobileHeBaoMoban");
        //"F:\\桌面\\999220815147853_20221015_02.xls" ;
        if(StringUtils.isBlank(filePath)){
            return "模板未配置";
        }
        FileInputStream fis =null;
        Workbook wookbook = null;
        try {
            fis = new FileInputStream(filePath);
        } catch(Exception e){
            e.printStackTrace();
        }
        try {
            wookbook = new HSSFWorkbook(fis);
        } catch (Exception ex){
            ex.printStackTrace();
        }
        Sheet sheet = wookbook.getSheetAt(0);

        Row row1 = sheet.getRow(0);
        //总笔数
        row1.getCell(0).setCellValue(1);
        //总金额
        row1.getCell(1).setCellValue(price);
        Row row = sheet.getRow(4);
        Cell cell = row.getCell(0);
        //单个号码
        cell.setCellValue(phone);
        cell = row.getCell(1);
        // 单笔金额
        cell.setCellValue(price);
        File file = new File(CookieRedis.get("exportPath")+"/"+fileName+".xls");
        //文件输出流
        FileOutputStream outStream;
        try {
            outStream = new FileOutputStream(file);
            wookbook.write(outStream);
            outStream.flush();
            outStream.close();
            System.out.println("上传代缴文件成功！上传代缴文件导出路径：--"+file.getAbsolutePath());
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}

